<template>
  <el-container>
    <aside-layout></aside-layout>
    <el-main>
      <el-row :gutter="20">
        <!-- 美化后的统计信息模块 -->
        <el-col :span="8">
          <el-card shadow="hover" class="statistics-card">
            <div slot="header" class="clearfix">
              <span>统计信息</span>
            </div>
            <div class="statistics">
              <div class="stat-item">
                <i class="el-icon-user-solid stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">总人数</p>
                  <p class="stat-value">{{ elderlyList.length }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-s-home stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">在住人数</p>
                  <p class="stat-value">{{ inResidenceCount }}</p>
                </div>
              </div>
              <div class="stat-item">
                <i class="el-icon-s-check stat-icon"></i>
                <div class="stat-content">
                  <p class="stat-title">离院人数</p>
                  <p class="stat-value">{{ outResidenceCount }}</p>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>

        <!-- 健康状况图表 -->
        <el-col :span="16">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>健康状况分布</span>
            </div>
            <div ref="healthChart" style="height: 300px;"></div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 老人管理表格 -->
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="24">
          <el-card shadow="hover">
            <div slot="header" class="clearfix">
              <span>老人管理</span>
              <el-button type="primary" icon="el-icon-plus" @click="handleAdd" style="float: right;" v-tooltip="'新增老人'">新增老人</el-button>
            </div>
            <div class="operation-bar">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索姓名"
                prefix-icon="el-icon-search"
                style="width: 200px; margin-right: 20px;"
                @keyup.enter.native="handleSearch"
              ></el-input>
              <el-select v-model="filterStatus" placeholder="选择状态" style="width: 150px;">
                <el-option label="全部" value=""></el-option>
                <el-option label="在住" value="在住"></el-option>
                <el-option label="离院" value="离院"></el-option>
              </el-select>
            </div>
            <el-table :data="filteredElderlyList" style="width: 100%" border>
              <el-table-column prop="name" label="姓名" width="120"></el-table-column>
              <el-table-column prop="age" label="年龄" width="80"></el-table-column>
              <el-table-column prop="room" label="房间号" width="100"></el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template slot-scope="scope">
                  <el-tag :type="scope.row.status === '在住' ? 'success' : 'info'" v-tooltip="scope.row.status">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="health" label="健康状况" width="120"></el-table-column>
              <el-table-column prop="contact" label="紧急联系人" width="150"></el-table-column>
              <el-table-column prop="admissionDate" label="入住时间" width="150"></el-table-column>
              <el-table-column prop="medicalRecords" label="医疗记录" width="150"></el-table-column>
              <el-table-column prop="activityParticipation" label="活动参与" width="150"></el-table-column>
              <el-table-column prop="dietaryPreferences" label="饮食偏好" width="150"></el-table-column>
              <el-table-column label="操作" width="180">
                <template slot-scope="scope">
                  <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
                  <el-button type="text" @click="handleDelete(scope.row)" class="delete-btn">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>

      <!-- 新增/编辑老人对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
        <el-form :model="form" label-width="120px">
          <el-form-item label="姓名">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="年龄">
            <el-input v-model="form.age"></el-input>
          </el-form-item>
          <el-form-item label="房间号">
            <el-input v-model="form.room"></el-input>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="选择状态">
              <el-option label="在住" value="在住"></el-option>
              <el-option label="离院" value="离院"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="健康状况">
            <el-input v-model="form.health"></el-input>
          </el-form-item>
          <el-form-item label="紧急联系人">
            <el-input v-model="form.contact"></el-input>
          </el-form-item>
          <el-form-item label="入住时间">
            <el-date-picker v-model="form.admissionDate" type="date" placeholder="选择日期"></el-date-picker>
          </el-form-item>
          <el-form-item label="医疗记录">
            <el-input v-model="form.medicalRecords"></el-input>
          </el-form-item>
          <el-form-item label="活动参与">
            <el-input v-model="form.activityParticipation"></el-input>
          </el-form-item>
          <el-form-item label="饮食偏好">
            <el-input v-model="form.dietaryPreferences"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </div>
      </el-dialog>
    </el-main>
  </el-container>
</template>

<script>
import AsideLayout from '@/layout/asideLayout.vue'
import * as echarts from 'echarts'
import axios from 'axios'

export default {
  components: {
    AsideLayout
  },
  name: 'ElderlyManagement',
  data() {
    return {
      searchKeyword: '',
      filterStatus: '',
      elderlyList: [],
      dialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        name: '',
        age: '',
        room: '',
        status: '',
        health: '',
        contact: '',
        admissionDate: '',
        medicalRecords: '',
        activityParticipation: '',
        dietaryPreferences: ''
      },
      healthChartOptions: {
        title: {
          text: '健康状况分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          top: 'bottom'
        },
        series: [
          {
            name: '健康状况',
            type: 'pie',
            radius: '50%',
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
    }
  },
  computed: {
    filteredElderlyList() {
      return this.elderlyList.filter(elderly => {
        const matchesKeyword = this.searchKeyword === '' || elderly.name.includes(this.searchKeyword)
        const matchesStatus = this.filterStatus === '' || elderly.status === this.filterStatus
        return matchesKeyword && matchesStatus
      })
    },
    inResidenceCount() {
      return this.elderlyList.filter(elderly => elderly.status === '在住').length
    },
    outResidenceCount() {
      return this.elderlyList.filter(elderly => elderly.status === '离院').length
    }
  },
  mounted() {
    this.fetchElderlyList()
      .then(() => {
        this.initCharts()
      })
  },
  methods: {
    fetchElderlyList() {
      return axios.get('http://localhost:3000/api/elderly')
        .then(response => {
          this.elderlyList = response.data
          this.updateHealthChartData()
        })
        .catch(error => {
          console.error('Error fetching elderly list:', error)
        })
    },
    initCharts() {
      const chartContainer = this.$refs.healthChart
      const chartInstance = echarts.init(chartContainer)
      this.updateHealthChartData()
      chartInstance.setOption(this.healthChartOptions)
    },
    updateHealthChartData() {
      const healthCounts = this.elderlyList.reduce((acc, elderly) => {
        acc[elderly.health] = (acc[elderly.health] || 0) + 1
        return acc
      }, {})

      const totalElderly = this.elderlyList.length;
      this.healthChartOptions.series[0].data = Object.entries(healthCounts).map(([key, value]) => ({
        name: key,
        value: totalElderly ? (value / totalElderly) * 100 : 0
      }))
      const chartContainer = this.$refs.healthChart;
      const chartInstance = echarts.init(chartContainer);
      chartInstance.setOption(this.healthChartOptions);
    },
    handleAdd() {
      this.dialogTitle = '新增老人'
      this.form = {
        id: null,
        name: '',
        age: '',
        room: '',
        status: '',
        health: '',
        contact: '',
        admissionDate: '',
        medicalRecords: '',
        activityParticipation: '',
        dietaryPreferences: ''
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑老人'
      this.form = { ...row }
      this.dialogVisible = true
    },
    handleSubmit() {
      if (this.form.id) {
        axios.put(`http://localhost:3000/api/elderly/${this.form.id}`, this.form)
          .then(() => {
            this.fetchElderlyList()
            this.dialogVisible = false
            this.$message.success('更新老人信息成功')
          })
          .catch(error => {
            console.error('Error updating elderly:', error)
            this.$message.error('更新老人信息失败')
          })
      } else {
        axios.post('http://localhost:3000/api/elderly', this.form)
          .then(() => {
            this.fetchElderlyList()
            this.dialogVisible = false
            this.$message.success('新增老人成功')
          })
          .catch(error => {
            console.error('Error adding elderly:', error)
            this.$message.error('新增老人失败')
          })
      }
    },
    handleDelete(row) {
      this.$confirm(`确认删除老人 ${row.name} 吗？`, '提示', {
        type: 'warning'
      }).then(() => {
        axios.delete(`http://localhost:3000/api/elderly/${row.id}`)
          .then(() => {
            this.fetchElderlyList()
            this.$message.success('删除成功')
          })
          .catch(error => {
            console.error('Error deleting elderly:', error)
            this.$message.error('删除失败')
          })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    }
  },
  watch: {
    elderlyList: {
      handler() {
        this.updateHealthChartData()
      },
      deep: true
    }
  }
}
</script>

<style scoped>
.el-main {
  padding: 20px;
}

.el-card {
  transition: transform 0.3s;
}

.el-card:hover {
  transform: translateY(-5px);
}

.operation-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.delete-btn {
  color: #F56C6C;
}

.delete-btn:hover {
  color: #f78989;
}

.statistics {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-item {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 5px;
}

.stat-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 10px;
}

.stat-content {
  display: flex;
  flex-direction: column;
}

.stat-title {
  font-size: 14px;
  color: #606266;
}

.stat-value {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

/* 添加全局适应样式 */
.el-container {
  height: 100vh; /* 使容器高度适应视口 */
}

.el-main {
  padding: 20px;
  overflow: auto; /* 允许内容溢出时滚动 */
}

/* 媒体查询以适应不同屏幕尺寸 */
@media (max-width: 768px) {
  .operation-bar {
    flex-direction: column; /* 在小屏幕上垂直排列 */
  }

  .operation-bar el-input,
  .operation-bar el-select {
    width: 100%; /* 输入框和选择框宽度适应 */
    margin-right: 0; /* 移除右边距 */
    margin-bottom: 10px; /* 添加底部间距 */
  }
}
</style>